﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.Timers;
using System.ServiceModel;
using EpiPoker.NotifyService;
using EpiPoker.DataAccess;
using System.Threading;


namespace EpiPoker
{
    public partial class Table : System.Web.UI.Page
    {
        #region attributes
        protected AppFacebookService objFbService = new AppFacebookService();
        private static List<Seat> list_seat = null;
        private static List<Seat> list_player = null;
        private static int nbPlayer;
        private static int category;
        private static Objects.Deck deck = new Objects.Deck();
        private static List<Objects.Card> cards = new List<Objects.Card>();
        private static int blind = 0;
        private static int pot = 0;
        private static long idtable;
        private static int userPlaying = 0;
        #endregion

        #region getters/setters
        public static long Idtable
        {
            get { return idtable; }
            set { idtable = value; }
        }

        public static int UserPlaying
        {
            get { return Table.userPlaying; }
            set { Table.userPlaying = value; }
        }

        public static int Pot
        {
            get { return Table.pot; }
            set { Table.pot = value; }
        }
        public static int Category
        {
            get { return Table.category; }
            set { Table.category = value; }
        }

        public static int NbPlayer
        {
            get { return Table.nbPlayer; }
            set { Table.nbPlayer = value; }
        }

        public static List<Seat> List_seat
        {
            get { return Table.list_seat; }
            set { Table.list_seat = value; }
        }

        public static int Blind
        {
            get { return Table.blind; }
            set { Table.blind = value; }
        }

        public static List<Seat> List_player
        {
            get { return Table.list_player; }
            set { Table.list_player = value; }
        }

        public long getIdTable()
        {
            return idtable;
        }

        public List<Seat> getListSeat()
        {
            return list_seat;
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            T_User userToPlace = DataAccess.User.GetUser(long.Parse(Session["facebook_userId"].ToString()));
            T_Table table = DataAccess.Table.GetTable((long)userToPlace.IdTable);
            idtable = table.idTable;

            if (table.idCategory == 1)
                Category = 10;
            else
                Category = 100;

            Seat1.Number = 0;
            Seat2.Number = 1;
            Seat3.Number = 2;
            Seat4.Number = 3;
            Seat5.Number = 4;
            Seat6.Number = 5;
            Seat7.Number = 6;
            Seat8.Number = 7;
            Seat9.Number = 8;
            Seat10.Number = 9;

            if (list_seat == null)
            {
                list_seat = new List<Seat>();
                list_seat.Add(Seat1);
                list_seat.Add(Seat2);
                list_seat.Add(Seat3);
                list_seat.Add(Seat4);
                list_seat.Add(Seat5);
                list_seat.Add(Seat6);
                list_seat.Add(Seat7);
                list_seat.Add(Seat8);
                list_seat.Add(Seat9);
                list_seat.Add(Seat10);
            }

            if (!IsPostBack)
            {
                RaiseValue.Text = "0";
                First.Visible = false;
                Second.Visible = false;
                Third.Visible = false;
                Fourth.Visible = false;
                Fifth.Visible = false;
            }
        }

        protected void Refresher(object sender, EventArgs e)
        {
            UpdatePanel2.Update();
            UpdatePanel2.DataBind();
        }

        protected void Leave_Table(object sender, EventArgs e)
        {
            T_User userToPlace = DataAccess.User.GetUser(long.Parse(Session["facebook_userId"].ToString()));

            userToPlace.IdTable = null;
            userToPlace.NumPlace = null;
            DataAccess.User.UpdateUser(userToPlace);

            int del = 0;
            int reff = 0;

            if (list_player != null)
            {
                for (int i = 0; i < list_player.Count; i++)
                {
                    if (list_player[i].User.IdUser == long.Parse(Session["facebook_userId"].ToString()))
                    {
                        del = i;
                        reff = list_player[i].Number;
                        break;
                    }
                }

                list_player.RemoveAt(del);
            }

            if (list_seat != null)
            {
                for (int i = 0; i < list_seat.Count; i++)
                {
                    if (list_seat[i].Number == reff)
                    {
                        del = i;
                        break;
                    }
                }

                list_seat[del].IsPlaying = false;
                list_seat[del].User = new T_User();
            }

            Response.Redirect("Default.aspx");         
        }

        public void UpdateTable()
        {
            Seat1.IsPlaying = true;
            UpdatePanel2.Focus();
        }

        public static void HideSitButtons(Seat EventSeat)
        {
            foreach (var seat in List_seat)
            {
                if (seat.User.IdUser != EventSeat.User.IdUser)
                    seat.HideSitButton();

                //T_User tmp = DataAccess.User.GetUser(seat.User.IdUser);

                //if (tmp != null)
                //{
                //    seat.IsPlaying = true;
                //    seat.User = User;

                //    if (Table.List_player == null)
                //        Table.List_player = new List<Seat>();

                //    Table.List_player.Add(this);
                //    Table.NbPlayer++;
                //}
            }
        }

        public static void BeginGame()
        {
            deck = new Objects.Deck();
            deck = BusinessManagementObjects.DeckActions.mixer(deck);
               
            List<T_User> list_user = new List<T_User>();
            list_player = new List<Seat>();

            foreach (var seat in list_seat)
            {
                if (seat.IsPlaying)
                {
                    list_player.Add(seat);
                    list_user.Add(seat.User);
                }
            }

            List<Objects.Hand> Hands = BusinessManagementObjects.DeckActions.distribute(list_user, deck);

            Random random = new Random();

            list_player[random.Next(0, list_player.Count)].IsDealer = true;

            for (int i = 0; i < Hands.Count; i++)
            {
                list_player[i].Hand = Hands[i];
                list_player[i].PrintHand();

                if (list_player[i].IsDealer)
                {
                    list_player[i].IsBigBlind = false;
                    list_player[i].IsDealer = true;

                    if (list_player.Count == 2)
                    {
                        list_player[i].IsSmallBlind = true;
                        list_player[i].Play = true;
                        userPlaying = list_player[i].Number;
                        list_player[i].Change();

                        if (i == Hands.Count - 1)
                        {
                            list_player[0].IsBigBlind = true;
                            list_player[0].IsSmallBlind = false;
                            list_player[0].IsDealer = false;
                            list_player[0].Play = false;
                            list_player[0].Change();
                        }
                        else
                        {
                            list_player[i + 1].IsBigBlind = true;
                            list_player[i + 1].IsSmallBlind = false;
                            list_player[i + 1].IsDealer = false;
                            list_player[i + 1].Play = false;
                            list_player[i + 1].Change();
                        }
                    }
                }
            }
            
            Blind = Category * 2;

            foreach (var item in list_player)
            {
                if (item.Number == userPlaying)
                    item.PlayRound();
            }
        }

        public void checkRound(Seat seat)
        {
            int mise = seat.GetBet();

            if (list_player.Count == 1)
            {
                T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(list_player[0].User.IdUser);
                int amount = (int)portfolio.Amount;

                amount += Pot + mise;
                portfolio.Amount = amount;
                DataAccess.Portfolio.UpdatePortfolio(portfolio);

                Pot = 0;
                Blind = Category;
                deck = null;

                First.ImageUrl = "";
                Second.ImageUrl = "";
                Third.ImageUrl = "";
                Fourth.ImageUrl = "";
                Fifth.ImageUrl = "";

                First.Visible = false;
                Second.Visible = false;
                Third.Visible = false;
                Fourth.Visible = false;
                Fifth.Visible = false;

                list_player[0].Fallcard();

                foreach (var item in list_seat)
                {
                    if (item.User.IdUser != 0 && item.User.IdUser != list_player[0].User.IdUser)
                        list_player.Add(item);
                }

                //BeginGame();
                Response.Redirect("Table.aspx");
            }
            else
            {
                for (int i = 0; i < list_player.Count; i++)
                {
                    if (list_player[i].Number == userPlaying)
                    {
                        if (i == (list_player.Count - 1))
                            userPlaying = list_player[0].Number;
                        else
                            userPlaying = list_player[i + 1].Number;

                        if (Blind == list_player[i].BetPlayer)
                        {
                            Blind = 0;
                            list_player[i].BetPlayer = 0;

                            if (First.ImageUrl == "")
                            {
                                Flop();
                                foreach (var item in list_player)
                                {
                                    if (item.Number == userPlaying)
                                    {
                                        item.PlayRound();
                                        break;
                                    }
                                }
                            }
                            else if (Fourth.ImageUrl == "")
                            {
                                Turn();
                                foreach (var item in list_player)
                                {
                                    if (item.Number == userPlaying)
                                    {
                                        item.PlayRound();
                                        break;
                                    }
                                }
                            }
                            else if (Fifth.ImageUrl == "")
                            {
                                River();
                                foreach (var item in list_player)
                                {
                                    if (item.Number == userPlaying)
                                    {
                                        item.PlayRound();
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                List<Objects.Hand> list_users = new List<Objects.Hand>();

                                foreach (var item in list_player)
                                {
                                    list_users.Add(item.Hand);
                                }

                                DataAccess.T_User res = BusinessManagementObjects.Winner.winner(cards, list_users);//BusinessManagement.Gagnant.winner(cards, list_users);

                                if (res.IdUser != 0)
                                {
                                    T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(res.IdUser);
                                    int amount = (int)portfolio.Amount + Pot;

                                    portfolio.Amount = amount;

                                    DataAccess.Portfolio.UpdatePortfolio(portfolio);

                                    foreach (var item in list_player)
                                    {
                                        if (res.IdUser == item.User.IdUser)
                                        {
                                            item.SetGain(amount);
                                            //item.fallCard();
                                        }
                                    }
                                }
                                else
                                {
                                    int value = Pot / list_users.Count;

                                    foreach (var item in list_player)
                                    {
                                        T_Portfolio portfolio = DataAccess.Portfolio.GetPortfolioByUserId(item.User.IdUser);
                                        int amount = (int)portfolio.Amount + value;

                                        portfolio.Amount = amount;

                                        DataAccess.Portfolio.UpdatePortfolio(portfolio);

                                        item.SetGain(amount);
                                    }
                                }

                                First.ImageUrl = "";
                                Second.ImageUrl = "";
                                Third.ImageUrl = "";
                                Fourth.ImageUrl = "";
                                Fifth.ImageUrl = "";

                                First.Visible = false;
                                Second.Visible = false;
                                Third.Visible = false;
                                Fourth.Visible = false;
                                Fifth.Visible = false;

                                deck = null;

                                //BeginGame();
                                Response.Redirect("Table.aspx");
                            }
                        }
                    }
                }
            }
        }

        public void Flop()
        {
            List<Objects.Card> flop = BusinessManagementObjects.DeckActions.flop(deck);//BusinessManagement.Melangeur.flop(deck);

            cards = flop;

            First.ImageUrl = "Images/Card/" + (Objects.Color)flop[0].Color + "/" + (Objects.Type)flop[0].Value + ".png";
            Second.ImageUrl = "Images/Card/" + (Objects.Color)flop[1].Color + "/" + (Objects.Type)flop[1].Value + ".png";
            Third.ImageUrl = "Images/Card/" + (Objects.Color)flop[2].Color + "/" + (Objects.Type)flop[2].Value + ".png";

            First.Visible = true;
            Second.Visible = true;
            Third.Visible = true;
        }

        protected void Turn()
        {
            Objects.Card turn = BusinessManagementObjects.DeckActions.turn(deck);//BusinessManagement.Melangeur.turn(deck);

            cards.Add(turn);

            Fourth.ImageUrl = "Images/Card/" + (Objects.Color)turn.Color + "/" + (Objects.Type)turn.Value + ".png";
            Fourth.Visible = true;
        }

        protected void River()
        {
            Objects.Card river = BusinessManagementObjects.DeckActions.river(deck);//BusinessManagement.Melangeur.river(deck);

            cards.Add(river);

            Fifth.ImageUrl = "Images/Card/" + (Objects.Color)river.Color + "/" + (Objects.Type)river.Value + ".png";
            Fifth.Visible = true;
        }

        protected void FoldClick(object sender, EventArgs e)
        {
            foreach (var item in list_seat)
            {
                if (item.Number == userPlaying)
                    item.FoldAction();
            }
        }

        protected void Call(object sender, EventArgs e)
        {
            if (cards.Count == 0)
            {
                Flop();
                Turn();
                River();

                List<Objects.Hand> hands = new List<Objects.Hand>();

                foreach (var item in list_player)
	            {
		            hands.Add(item.Hand);
	            }
                
                //Fold.Text = BusinessManagementObjects.Winner.winner(cards, hands).FirstName;   
            }

            foreach (var item in list_seat)
            {
                if (item.Number == userPlaying)
                    item.CallAction();
            }
        }

        protected void RaiseClick(object sender, EventArgs e)
        {
            foreach (var item in list_seat)
            {
                if (item.Number == userPlaying)
                    item.RaiseAction(int.Parse(RaiseValue.Text));
            }
        }

        protected void test(object sender, EventArgs e)
        {
            Flop();
        }
    }
}